﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.SdkTypeProxy.Metadata;

namespace SalesTracker.Tools.EntityComparer.Lib
{
    public class CrmMetadataServiceAdapter
    {
        private string CrmUrl;

        public CrmMetadataServiceAdapter(string url)
        {
            this.CrmUrl = url;
        }

        /// <summary>
        /// returns crm service
        /// </summary>
        /// <returns></returns>
        public MetadataService NewCrmservice(NetworkCredential credetials)
        { 
            var uri =  Uri.IsWellFormedUriString(CrmUrl, UriKind.Absolute);
            if(!uri)
            {
                 throw new ApplicationException("The Url Specifield is not valid- please supply a full path - go to crm on your browser and supply the full path copied from your browser.");
            }

            // Set up the CRM service.
            var token = new CrmAuthenticationToken();
            token.AuthenticationType =0;
            token.OrganizationName = GetOrgNameFromUrl();
          
            
            var service = new MetadataService();
            service.Url = GetServerAndPortFromUrl();
            service.Url += "mscrmservices/2007/MetadataService.asmx";
            service.CrmAuthenticationTokenValue = token;
            service.Credentials = credetials;

            return service;
        }

        /// <summary>
        /// Gets server and port (host)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetServerAndPortFromUrl()
        {
           var serverandport = new Uri(CrmUrl);

            return string.Format("http://{0}",serverandport.Authority);
        }

        /// <summary>
        /// gets org name
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetOrgNameFromUrl()
        {
            
            var org = CrmUrl.Split('/')[3];
            return org;
        }
    }
}
